## Summary of Utils

This README summarizes the purpose of each file in this folder. For details on the specific inputs, outputs, and dependencies of each function, refer to documentation within the files.

#### Code for loading R environment and setting paths

- `load_utils.R` - This function loads required packages, both external packages and those in this repository.
  - `packages.txt` provides the list of required packages. It's passed to `pacman` which automatically installs packages in the active R environment if needed. 
  - Packages are loaded from this directory (which primarily contains functions specific to this analysis) and from `carleton_mortality_2022/utils/` which contains functions that are general across the Climate Impact Lab sectors.

#### Code for loading and manipulating data

- `impacts.R` - Contains functions that handle loading projected impacts from the projection output in `data/2_projection/3_impacts/`. Note that maintaining the folder structure within this directory is critical for these functions to operate correctly.

  - User functions:
    - `get_mortality_impacts` - Loads data from Monte Carlo projection output from CSV files generated by `quantiles.py` (See `2_run_projections`).
    - `get_mortality_impacts_single` - Loads data directly from the raw NetCDF4 output of a projection from a single climate model, RCP, IAM, SSP combination.
    - `get_mortality_covariates` - Loads covariates (`loggdppc` and `climtas`) from `allpreds` files, which are diagnostic files that are output along with projections from a single climate model.
  - Relevant input data directories:
    - `data/2_projection/3_impacts/`
  - Dependencies:
    - `region_tools.R`

- `region_tools.R` - Handles regional hierarchy in the analysis, e.g., impact regions, ADM1 agglomerations, countries. 

  - User functions:
    -  `check_resolution` - Determines whether an input region code is an impact region or an aggregation of impact regions, e.g., `USA.14.608` identifies the Cook County IL impact region whereas `USA.14` identifies all of Illinois.
    - `return_region_list` - Translates key words into list of impact region codes, e.g., `all` returns all 25k impact regions, `iso` returns country-level region codes, etc.
    - `get_children` - Returns a list of impact regions within an input aggregated regions, e.g., `USA` returns all ~3000 impact regions within the US.
  - Relevant input data directories:
    - `data/2_projection/1_regions/hierarchy.csv`

- `econvar.R`- Loads "economic" variables (income, income per capita, and population) from stored datasets and provides helper functions for population-weighted averages.

  - User functions:
    - `get_econvar` - Loads population, income, and income per capita data from the SSP projections. Income values are in 2019$ PPP.
    - `popwt_collapse_to_region` - performs a population weighted collapse of impact regions within a more aggregated region.
    - `popwt_collapse_rows` - population-weighted collapse of rows in a data frame or `data.table`.
    - `popwt_collapse_columns` - performs a population-weighted average of age-group specific columns in a data frame or `data.table`, e.g., finding the average temperature sensitivity of mortality at 35C requires collapsing over age-specific sensitivities.
  - Relevant input data directories:
    - `data/2_projection/2_econ_vars`
  - Dependencies:
    - `region_tools.R`

- `damages.R` - Loads monetized mortality damages. Note that this function loads outputs from the next step in the analysis `3_valuation`, but for simplicity of the code base and since it's mostly needed for in-text summary stats and communications purposes, we keep the code here. Like `impacts.R`, it relies upon a set folder structure in `data/3_valuation`.

  - User functions:
    - `get_mortality_damages` - Loads monetized mortality damages from the output of `3_valuation/2_calculate_damages`. Damages are output in 2019$ PPP or share of GDP.
    - `update_damages_units` - Not a user function but worth mentioning. Late in the analysis we decided to use a VSL that is more consistent with the one EPA currently uses. This requires several adjustment factors be applied post-process: (1) Inflation adjustment which converts damages from 2005$ to 2019$, (2) VSL adjustment which converts the VSL from an outdated value to the most recent value based upon 2020 incomes (see Carleton et al. 2019 for the source) and, (3) Income growth adjustment, which converts the denominator of our income scaling factor from 2005 Incomes to 2020 Incomes (consistent with the latest EPA VSL).
  - Relevant input data directories:
    - `data/3_valuation/impact_region`
    - `data/3_valuation/inputs`
  - Dependencies:
    - `region_tools.R`

  #### Code for visualizing data

- `calculate.betas.R` - Calculates response functions for purposes of plotting responses and visualizing temperature sensitivity (e.g., beta maps).

  - User functions:
    - `calculate.beta` - Calculates response functions for an input age group, CSVV, and covariate file. It also prepares some in-text summary stats in the process of generating responses.
    - `plot.beta.maps` - Plots the spatial distribution of the temperature sensitivity of mortality (called "beta maps"). Relies upon the output of `calculate.beta`.
    - `plot.spaghetti`- Plots impact region level response functions and the unweighted average across regions. Relies upon the output of `calculate.beta`.
    - `plot.delta.map` - Plots the _change_ in the temperature sensitivity of mortality between two years for a given age group. Relies upon the output of `calculate.beta`.
  - Relevant input data directories:
    - `data/2_projection/main_specification/` (for CSVV, MMT, covariates)
  - Relevant output directories:
    - `output/figures/Figure_3_D5_beta_maps` (beta maps)
    - `output/figures/Figure_3_D5_spaghettis`(response functions)
    - `output/figures/Figure_E2_delta_maps`(delta maps)
  - Dependencies:
    - `carleton_mortality_2022utils/ggspaghetti.R`

- `insample_data_coverage.R` - Generates Figure B1 in the Carleton et al. (2022), which shows the in-sample data coverage of mortality's estimation sample.

  - User functions:
    - `insample_data_coverage`- Generates map.
  - Relevant input data directories:
    - `data/1_estimation/3_regions`
  - Relevant output directories:
    - `output/figures/Figure_B1_data_coverage`

- `covariate_coverage.R`- Generates Figure 2 in Carleton et al. (2022), which compares in-sample vs. global loggdppc and climtas distributions in 2010 and 2100. 

  - User functions:
    - `insample_data_coverage`- Generates heat map.

  - Relevant output directories:
    - `output/figures/Figure_2_covariate_coverage`
  - Dependencies:
    - `impacts.R:::get_mortality_covariates`

- `impact_map.R` - Generates maps of projected mortality impacts.

  - User functions:
    - `quick_map` - Utility function for calling `impacts.R` functions and plotting projection output.
    - `mortality_impacts_map` - Generates map of the mortality risk of future climate change (Figures 4, F1, F6)
    - `mortality_impacts_map_all_adaptation` - Generates maps for each adaptation scenario
  - Relevant output directories:
    - `output/figures/Figure_4_impact_maps`
    - `output/figures/Figure_F1_impact_maps`
    - `output/figures/Figure_F6_impact_maps`
  - Dependencies:
    - `impacts.R`
    - `morality/utils/mapping.R`

- `density_plots.R` - Generates density plots providing the full distribution of estimated mortality impacts across all Monte Carlo simulations.

  - User functions:
    - `impacts_density_plot.R` - generates density plot across GCMs and batches. Plots GCM-weighted average of monte carlo draws and shades at 1, 2, and 3 standard deviations. (Figure 4 density plots)
  - Relevant output directories:
    - `output/figures/Figure_4_density_plots`
  - Dependencies:
    - `impacts.R:::get_mortality_impacts`
    - `carleton_mortality_2022utils/ggkd.R`

- `timeseries.R` - Produces time series of projected impacts.

  - User functions:
    - `multi_timeseries` - Utility function for calling `impacts.R` functions and plotting the output. Supports multiple calls for producing comparisons of time series on the same plot.
    - `timeseries_compare_adaptation` - Generates time series comparing adaptation scenarios (Figure 5 Panel A).
    - `timeseries_compare_rcp` - Generates time series with uncertainty and boxplots comparing RCPs at end of century (Figure 5 Panel B).
    - `imeseries_compare_age_groups` - Heterogeneity in climate change impacts on mortality by age group (Figure F4).
    - `timeseries_compare_ssp_iam` - The full mortality risk of climate change under different scenarios of population growth, economic growth, and emissions (Figure F5).
    - `timeseries_compare_binnned` - Robustness of impact projections to alternate functional forms of temperature  (Figure F9).
    - `timeseries_linear_extrapolation` - Robustness of impact projections to various linear extrapolations (Figure F10)
    -  `timeseries_flexadapt_rate` - Impacts of climate change on mortality are qualitatively similar with a model of slower or faster adaptation rates (Figure F11).
  - Relevant output directories:
    - `output/figures/Figure_5_timeseries`
    - `output/figures/Figure_F4_timeseries`
    - `output/figures/Figure_F5_timeseries`
    - `output/figures/Figure_F9_timeseries`
    - `output/figures/Figure_F10_timeseries`
    - `output/figures/Figure_F11_timeseries`
  - Dependencies:
    - `impacts.R`
    - `morality/utils/ggtimeseries.R`

- `barchart.R` - Produces impacts at terciles of the income and climate distributions for purposes of the bar chart in Figures 9 and F8.

  - User functions
    - `mortality_barchart` - Generates CSV file containing data required to generate Figures 9 and F8.
      - RA note: values from this function are manually input into the excel spreadsheet in the output folder. We need to use excel here because no other plotting method allows us to manually arrange the order in which the bars are stacked. From there, a lot of processing happens in Illustrator before we get the final figure for the paper.
  - Relevant output directories:
    - `output/figures/Figure_9_barchart`
    - `output/figures/Figure_F8_barchart`
  - Dependencies
    - `impacts.R:::get_mortality_impacts`
    - `impacts.R:::get_mortality_covariates`
    - `econvar.R:::get_econvar`

- `alt_deciles.R` - Produces box-and-whisker plots of future impacts at deciles of today's income and climate distributions (Figure 6)

  - User functions
    - `deciles_plot_new`- Produces plot for a given covariate and scenario.
  - Relevant output directories
    - `output/figures/Figure_6_deciles`
  - Dependencies
    - `impacts.R:::get_mortality_impacts`
    - `impacts.R:::get_mortality_covariates`
    - `econvar.R:::get_econvar`

  

